package cn.chencq.proxy.timer.service;

import java.net.Proxy;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.chencq.proxy.constants.RedisKey;
import cn.chencq.proxy.util.Util;

import com.limei.adplatform.redis.cluster.RedisClusterFactory;

/**
 * ip查询网址 http://1212.ip138.com/ic.asp http://www.ip138.com/
 * 
 * @author chencq
 * 
 */
public class ProxyCheckCallable implements Callable<Integer> {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProxyIPService.class);

	private Set<String> proxy;
	private int page;

	public ProxyCheckCallable(Set<String> proxy, int page) {
		this.proxy = proxy;
		this.page = page;
	}

	@Override
	public Integer call() throws Exception {
		String clusterName = RedisKey.getClusterName();
		String key = RedisKey.getVaildProxyKey();

		LOGGER.info("start check proxy,current page:{}", page);

		Set<String> valid = new HashSet<String>();
		int num = 0;
		for (String str : proxy) {
			Proxy p = Util.setProxy(str.split(":")[0], str.split(":")[1]);

			if (Util.checkProxy("http://www.ip138.com/", p)) {
				valid.add(str);
			} else {
				num += 1;
			}
		}

		LOGGER.info("check proxy end ,current page:{},vaild proxy size:{}", page, valid.size());
		// 将有效的代理放入
		if (valid.size() > 0) {
			RedisClusterFactory.sadd(clusterName, key, Util.setToArray(valid));
		}

		return num;
	}
}
